package com.sanri.tools.modules.page.service;

import com.alibaba.fastjson.JSON;
import com.sanri.tools.modules.core.service.cc.CommonConfigService;
import com.sanri.tools.modules.core.service.connect.FileBaseConnectService;
import com.sanri.tools.modules.core.service.file.FileManager;
import com.sanri.tools.modules.page.service.dto.pageconfig.PageConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huangzhengri
 * 这个 bean 要在资源和菜单之前初始化, 以便把资源和菜单信息进行注入
 */
@Service
@Slf4j
@Order(Integer.MAX_VALUE - 1000)
public class PageManager implements InitializingBean {
    @Autowired
    private FileManager fileManager;
    @Autowired
    private FileBaseConnectService connectService;

    @Autowired
    private CommonConfigService commonConfigService;

    public static final String MODULE = "pageconfig";

    @Autowired
    private BeanFactory beanFactory;

    @Override
    public void afterPropertiesSet() throws Exception {
        injectResourceAndMenus();
    }

    /**
     * 加载页面配置
     * @param name
     * @return
     * @throws IOException
     */
    public PageConfig loadPageConfig(String name) throws IOException {
        final String content = commonConfigService.readTemplateFileContent("pageconfig.json", name);
        return JSON.parseObject(content,PageConfig.class);
    }

    /**
     * 重新注入菜单配置
     */
    public void reInjectResourceAndMenus() throws IOException {
        Object resourceRepository = beanFactory.getBean("resourceRepository");
        if (resourceRepository != null){
            Method afterPropertiesSet = MethodUtils.getMatchingAccessibleMethod(resourceRepository.getClass(), "afterPropertiesSet");
            ReflectionUtils.invokeMethod(afterPropertiesSet,resourceRepository);
        }
    }

    /**
     * 注入配置的资源和菜单到系统中
     */
    private void injectResourceAndMenus() throws IOException {
        // 获取页面名列表
        final String[] pageNames = commonConfigService.listTemplateFileNames("pageconfig.json");

        // 写入临时权限配置目录
        File security = fileManager.mkTmpDir("security");

        // 没有动态页面配置时, 删除菜单配置
        if (ArrayUtils.isEmpty(pageNames)){
            File file = new File(security, "pageDynamic.menus.conf");
            FileUtils.deleteQuietly(file);
            return ;
        }

        List<String> menus = new ArrayList<>();
        for (String pageName : pageNames) {
            String [] items = new String []{pageName,pageName,"/dynamicPage/"+pageName,"Menu","menu_level_1_dynamicPage","","/dynamicPage/"+pageName};
            menus.add(StringUtils.join(items,":"));
        }
        File file = new File(security, "pageDynamic.menus.conf");
        FileUtils.writeStringToFile(file,StringUtils.join(menus,"\n"),  StandardCharsets.UTF_8);
    }
}
